﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Magicodes.WeChat.Application.Authorization.Dto;
using Magicodes.WeChat.SDK.Apis.Token;
using Magicodes.WeChat.SDK;
using Magicodes.WeChat.SDK.Apis.OAuth;
using Abp.Domain.Repositories;
using Magicodes.WeChat.User;
using Magicodes.WeChat.User.Dto;
using Abp.Dependency;
using Abp.Timing;

namespace Magicodes.WeChat.Application.Authorization
{
    /// <summary>
    /// 微信授权相关接口
    /// </summary>
    public class WeChatAuthorizationAppService : IWeChatAuthorizationAppService
    {
        private readonly IRepository<WeChatUser, string> _weChatUserRepository;
        public WeChatAuthorizationAppService(IRepository<WeChatUser, string> weChatUserRepository)
        {
            _weChatUserRepository = weChatUserRepository;
        }
        /// <summary>
        /// 获取网页授权链接
        /// </summary>
        /// <param name="input">相关参数</param>
        /// <returns>网页授权链接</returns>
        public Task<string> GetAuthorizeUrl(GetAuthorizeUrlInput input)
        {
            var api = new OAuthApi();
            api.SetKey(key: input.Key ?? WeChatConfigManager.Current.GetKey());
            var url = api.GetAuthorizeUrl(input.RedirectUrl, input.State, input.OAuthScope);
            return Task.FromResult(url);
        }

        /// <summary>
        /// 获取oauthAccessToken[第二步]
        /// </summary>
        /// <returns></returns>
        public Task<OAuthTokenApiResult> GetOAuthToken(GetOAuthTokenInput input)
        {
            var api = new OAuthApi();
            api.SetKey(key: input.Key ?? WeChatConfigManager.Current.GetKey());
            var result = api.Get(input.Code).HanderApiResultError();
            return Task.FromResult(result);
        }

        /// <summary>
        ///  拉取用户信息(需scope为 snsapi_userinfo)[第三步]
        /// </summary>
        /// <returns>用户信息</returns>
        public Task<WeChatUserListDto> GetUserInfo(GetUserInfoInput input)
        {
            var weChatUserAppService = IocManager.Instance.Resolve<IWeChatUserAppService>();
            //从数据库或缓存中获取
            var weChatUser = weChatUserAppService.GetWeChatUserById(input.OpenId).Result;
            ;
            //如果粉丝信息不存在，则从接口获取并存储到数据库
            if (weChatUser == null)
            {
                var api = new OAuthApi();
                var tenantId = input.Key ?? WeChatConfigManager.Current.GetKey();
                api.SetKey(key: tenantId);
                var result = api.GetUserInfo(input.OauthAccessToken, input.OpenId, input.Lang ?? "zh_CN").HanderApiResultError();
                var weChatUserForEdit = new WeChatUserEditDto
                {
                    City = result.City,
                    Country = result.Country,
                    //GroupId = userInfo.groupid,
                    HeadImgUrl = result.Headimgurl,
                    //Language = userInfo.language,
                    NickName = result.NickName,
                    Id = result.OpenId,
                    Province = result.Province,
                    //Remark = userInfo.remark,
                    Sex = (int)result.Sex,
                    Subscribe = false,
                    SubscribeTime = DateTime.Now,
                    UnionId = result.Unionid,
                    TenantId = Convert.ToInt32(tenantId),
                    AppId = api.AppConfig.AppId
                };
                weChatUserAppService.CreateOrUpdateWeChatUser(new CreateOrUpdateWeChatUserDto { WeChatUser = weChatUserForEdit });
                weChatUser = new WeChatUserListDto()
                {
                    City = result.City,
                    Country = result.Country,
                    //GroupId = userInfo.groupid,
                    HeadImgUrl = result.Headimgurl,
                    //Language = userInfo.language,
                    NickName = result.NickName,
                    Id = result.OpenId,
                    Province = result.Province,
                    //Remark = userInfo.remark,
                    Sex = (int)result.Sex,
                    Subscribe = false,
                    SubscribeTime = DateTime.Now,
                    UnionId = result.Unionid,
                    CreationTime = Clock.Now,
                };

            }
            return Task.FromResult(weChatUser);
        }
    }
}
